﻿using System;
using System.Collections.Generic;
using System.Data.Objects.DataClasses;
using System.Dynamic;
using System.Linq;

namespace IGM.DataProvider
{
    public static class EntityHelper
    {
        public static dynamic GetProperties(this EntityObject obj)
        {
            return GetDynaObject(obj);
        }

        public static dynamic Properties(this Type type)
        {
            var properties = type.GetProperties();
            var propertyList = properties.ToDictionary(propertyInfo => propertyInfo.Name,
                                                                              propertyInfo => propertyInfo.Name);
            var myDyna = new DynamicUtility(propertyList, type.Name);
            return myDyna;
        }

        private static DynamicUtility GetDynaObject(object targetObject)
        {
            var properties = targetObject.GetType().GetProperties();
            var propertyList = properties.ToDictionary(propertyInfo => propertyInfo.Name,
                                                                              propertyInfo => propertyInfo.Name);
            var myDyna = new DynamicUtility(propertyList, targetObject.GetType().Name);
            return myDyna;
        }
    }

    public class DynamicUtility : DynamicObject
    {
        private readonly string _baseType;

        private readonly Dictionary<string, string> _properties;

        public DynamicUtility(Dictionary<string, string> properties, string baseType)
        {
            _properties = properties;
            _baseType = baseType;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                result = _properties[binder.Name];
                return true;
            }
            throw new Exception(string.Format("Property '{0}.{1}' is not existed.", _baseType, binder.Name));
        }
    }
}
